import React, { useCallback, useContext, useEffect } from "react";
import { Button, Colors, DateTimePicker, Picker, Switch, Text, TextField, View, ViewProps } from "react-native-ui-lib";
import { useTranslation } from "react-i18next";
import TaskChangeDateTime from "./task.change.date";
import { useChangeTimer, useInsertForm, useUpdateForm } from "@/hooks/task.form";
import { useColor } from "@/hooks/color";
import { useLoadedFontFamilyByAction } from "@/hooks/font";
import { BaseAddTaskCore, TaskType } from "./task.change";
import { router, useFocusEffect } from "expo-router";
import { ETaskPriority, taskEntity } from "@/drizzle/model/taskEntity";
import { Alert } from "react-native";
import { eq } from "drizzle-orm";
import { useKeyboard } from "@/hooks/keyboard";

const TaskCreateForm: React.FC<ViewProps> = () => {
  const query = useContext(BaseAddTaskCore);
  const filters: Array<{ label: string; type: ETaskPriority; value: number }> = [
    { label: useTranslation().t(ETaskPriority.IMPORTANT_AND_URGENT), type: ETaskPriority.IMPORTANT_AND_URGENT, value: 0 },
    { label: useTranslation().t(ETaskPriority.IMPORTANT_BUT_NOT_URGENT), type: ETaskPriority.IMPORTANT_BUT_NOT_URGENT, value: 1 },
    { label: useTranslation().t(ETaskPriority.NOT_IMPORTANT_BUT_URGENT), type: ETaskPriority.NOT_IMPORTANT_BUT_URGENT, value: 2 },
    { label: useTranslation().t(ETaskPriority.NOT_IMPORTANT_AND_NOT_URGENT), type: ETaskPriority.NOT_IMPORTANT_AND_NOT_URGENT, value: 3 },
    { label: useTranslation().t(ETaskPriority.DEFAULT), type: ETaskPriority.DEFAULT, value: 4 },
  ];
  // 任务执行时间
  const [dateTimer, setDateTimer] = React.useState<Date>(new Date());
  // 任务标题
  const [title, setTitle] = React.useState<string>("");
  // 任务描述
  const [description, setDescription] = React.useState<string>("");
  // 任务优先级 0:重要且紧急 1:重要且不紧急 2:紧急不重要 3:不重要不紧急 4:无
  const [priority, setPriority] = React.useState<{ label: string; type: ETaskPriority; value: number }>(filters[4]);
  // 任务状态 0:未完成 1:已完成
  const [status, setStatus] = React.useState<boolean>(false);

  useFocusEffect(
    useCallback(() => {
      setPriority(filters.find(item => item.type === query.item.priority) || filters[4]);
      setTitle(query.item.title);
      setDescription(query.item.content);
      setDateTimer(new Date(query.item.createdAt?.valueOf() || new Date().valueOf()));
      setStatus(query.item.status);
    }, [query.item.id])
  );

  const onPresbCreateIonic = async () => {
    if (title.length === 0) {
      Alert.alert("提示", "未输入任务标题", [], { cancelable: true });
      return;
    }
    if (description.length === 0) {
      Alert.alert("提示", "未输入任务描述", [], { cancelable: true });
      return;
    }
    if (query.type === "2008") {
      await useInsertForm
        .values({
          title: title,
          content: description,
          priority: priority.type || ETaskPriority.DEFAULT,
          createdAt: dateTimer,
          status: status || false,
          isProxy: false,
        })
        .execute();
    } else if (query.type === "2009") {
      await useUpdateForm
        .set({
          title: title,
          content: description,
          priority: priority.type || ETaskPriority.DEFAULT,
          createdAt: dateTimer,
          status: status || false,
          isProxy: false,
        })
        .where(eq(taskEntity.id, query.item.id))
        .execute();
    }
    if (router.canGoBack()) router.back();
  };

  const changeTimer = (date: Date, mode: React.ComponentProps<typeof DateTimePicker>["mode"]) => {
    setDateTimer(useChangeTimer(date, dateTimer, mode));
  };

  return (
    <View flex className='flex w-full'>
      <TextField
        label={useTranslation().t("7008")}
        labelColor={Colors.getColorTint(useColor().colors.text, 50)}
        placeholder={useTranslation().t("7003")}
        placeholderTextColor={Colors.getColorTint(useColor().colors.text, 40)}
        onChangeText={text => setTitle(text)}
        value={title}
        validate={["required"]}
        maxLength={10}
        style={{ ...useLoadedFontFamilyByAction("SPACE_MONO"), fontSize: 16, color: useColor().colors.text }}
        containerStyle={{ marginVertical: 15, borderBottomWidth: 1, borderBottomColor: Colors.getColorTint(useColor().colors.text, 60) }}
      />
      <TaskChangeDateTime
        label={useTranslation().t("7013")}
        mode='date'
        placeContent={useTranslation().t("6011")}
        changeDateTimer={date => changeTimer(date, "date")}
        value={dateTimer}
      />
      <TaskChangeDateTime
        label={useTranslation().t("7014")}
        mode='time'
        placeContent={useTranslation().t("6005")}
        changeDateTimer={date => changeTimer(date, "time")}
        value={dateTimer}
      />
      <TextField
        label={useTranslation().t("7009")}
        labelColor={Colors.getColorTint(useColor().colors.text, 50)}
        placeholder={useTranslation().t("7004")}
        placeholderTextColor={Colors.getColorTint(useColor().colors.text, 40)}
        onChangeText={text => setDescription(text)}
        value={description}
        maxLength={30}
        style={{ ...useLoadedFontFamilyByAction("SPACE_MONO"), fontSize: 16, color: useColor().colors.text }}
        containerStyle={{ marginVertical: 15, borderBottomWidth: 1, borderBottomColor: Colors.getColorTint(useColor().colors.text, 60) }}
      />
      <Picker
        label={useTranslation().t("7011")}
        labelColor={Colors.getColorTint(useColor().colors.text, 50)}
        placeholder={useTranslation().t("7006")}
        placeholderTextColor={Colors.getColorTint(useColor().colors.text, 40)}
        value={priority.value}
        onChange={items => setPriority(filters[items as number])}
        mode={Picker.modes.SINGLE}
        showSearch
        items={filters}
        style={{ ...useLoadedFontFamilyByAction("SPACE_MONO"), fontSize: 16, color: useColor().colors.text }}
        containerStyle={{ marginVertical: 15, borderBottomWidth: 1, borderBottomColor: Colors.getColorTint(useColor().colors.text, 60) }}
      />
      {/* 添加一个开关 */}
      <View
        style={{ marginVertical: 15, display: query.type == TaskType.EDIT_TASK ? "flex" : "none" }}
        className='flex flex-row w-full justify-between items-center'>
        <Text style={{ fontSize: 16, color: useColor().colors.text, ...useLoadedFontFamilyByAction("SPACE_MONO") }} className='flex'>
          {useTranslation().t("7012")}
        </Text>
        <Switch value={status} onValueChange={value => setStatus(value)} offColor={Colors.grey40} onColor={Colors.green30} />
      </View>
      <View className='absolute bottom-8 w-full gap-2'>
        <Button
          size='large'
          style={{ backgroundColor: Colors.getColorTint(useColor().color.action, 30), display: useKeyboard().keyboardVisible ? "none" : "flex" }}
          onPress={() => onPresbCreateIonic()}>
          <Text text70 style={{ color: useColor().colors.background, ...useLoadedFontFamilyByAction("SPACE_MONO") }} className='font-bold'>
            {query.useTitle[query.type].button}
          </Text>
        </Button>
      </View>
    </View>
  );
};

export default TaskCreateForm;
